package com.frogs.ucenter.v1.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.frogs.framework.util.PageList;
import com.frogs.framework.util.StringUtil;
import com.frogs.framework.util.date.DateUtil;
import com.frogs.system.util.OrderStatusEnum;
import com.frogs.system.util.UserRechargeableCardStatusEnum;
import com.frogs.system.web.api.request.Request;
import com.frogs.system.web.api.response.Response;
import com.frogs.system.web.exception.ServiceOperationException;
import com.frogs.ucenter.dao.UserRechargeBalanceDao;
import com.frogs.ucenter.dao.UserRechargeRecordDao;
import com.frogs.ucenter.dao.UserRechargeableCardDao;
import com.frogs.ucenter.entity.UserRechargeRecord;
import com.frogs.ucenter.entity.UserRechargeableCard;
import com.frogs.ucenter.util.Constants;
import com.frogs.ucenter.v1.request.UserRechargeableCardConsumeRequest;
import com.frogs.ucenter.v1.response.DefaultResponse;
import com.frogs.ucenter.v1.service.UserRechargeableCardService;
import com.frogs.ucenter.v1.util.ApiConstants;

@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
@Service(ApiConstants.VERSION+"userRechargeableCardService")
public class UserRechargeableCardServiceImpl extends UserRechargeStrategyBaseServiceImpl implements UserRechargeableCardService {
	
	private static final Logger log = LoggerFactory.getLogger(UserRechargeableCardServiceImpl.class);
	
	@Resource
	private UserRechargeableCardDao userRechargeableCardDao;
	
	@Resource
	private UserRechargeRecordDao userRechargeRecordDao;
	
	@Resource
	private UserRechargeBalanceDao userRechargeBalanceDao;

	/**
	 * 充值卡充值记录
	 */
	@Override
	public Response consume(Request request) throws Exception {
		DefaultResponse response = new DefaultResponse();
		try {
			UserRechargeableCardConsumeRequest userRechargeableCardRequest = (UserRechargeableCardConsumeRequest) request;
			log.info("func[consume] userRechargeableCardRequest[" + userRechargeableCardRequest.getUserId()+","+userRechargeableCardRequest.getRechargeCard() + "] ");
			
			HashMap<String, Object> params = new HashMap<String,Object>();
			params.put("eqCardPasswd",StringUtil.md5(userRechargeableCardRequest.getRechargeCard()+userRechargeableCardRequest.getCardPasswd(), Constants.ENCRYPT_RECHARGEABLE_CARD_KEY) );
			params.put("eqRechargeCard",userRechargeableCardRequest.getRechargeCard() );
			PageList<UserRechargeableCard> result = userRechargeableCardDao.selectByMap(params, 1, 1, false);
			
			if(result.size() == 0){
				throw new ServiceOperationException("充值卡号或密码有误");
			}
			
			UserRechargeableCard userRechargeableCard = result.get(0);
			int status = userRechargeableCard.getStatus();//卡状态
			//如果已经被其他人占用
			if(status == UserRechargeableCardStatusEnum.RUN_OUT.getId()){
				throw new ServiceOperationException("此卡号"+userRechargeableCardRequest.getRechargeCard() + "已经被使用过，不能重复核销");
			}else if(status == UserRechargeableCardStatusEnum.UNUSED.getId()){
				throw new ServiceOperationException("此卡号"+userRechargeableCardRequest.getRechargeCard() + "未激活，不能核销");
			}else if(status == UserRechargeableCardStatusEnum.FREEZING.getId()){
				throw new ServiceOperationException("此卡号"+userRechargeableCardRequest.getRechargeCard() + "已过期，不能核销");
			}
			
			/**修改充值卡信息*/
			userRechargeableCard.setActivateTime(new Date());
			userRechargeableCard.setStatus(UserRechargeableCardStatusEnum.RUN_OUT.getId());
			userRechargeableCard.setBalance(userRechargeableCard.getDenomination());
			userRechargeableCard.setUserId(userRechargeableCardRequest.getUserId());
			userRechargeableCard.setValidTime(DateUtil.getDateAfterYears(new Date(), 10));
			userRechargeableCardDao.update(userRechargeableCard);

			/**新增余额充值记录*/
			UserRechargeRecord userRechargeRecord = new UserRechargeRecord();
			userRechargeRecord.setRechargeCard(userRechargeableCardRequest.getRechargeCard());
			userRechargeRecord.setRechargeFrom(userRechargeableCardRequest.getRechargeFrom());
			userRechargeRecord.setRechargeMoney(userRechargeableCard.getDenomination());
			userRechargeRecord.setUserId(userRechargeableCardRequest.getUserId());
			userRechargeRecord.setStatus(OrderStatusEnum.ORDER_STATUS_YES.getId());
			userRechargeRecordDao.insert(userRechargeRecord);
			
			/**修改用户余额*/
			super.rechargeBalance(userRechargeableCard.getDenomination(), userRechargeableCardRequest.getUserId());
			response.setTip("充值成功");
			
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
}